<template>
  <div>
    <!--    序列号相关详情 Start-->
    <!--    序列号分类-->
    <a-form
      v-if="rule.level === 1"
      class="no-bottom-form column-two-form"
      layout="inline"
      style="width: 100%;margin: 0 auto;"
    >
      <a-form-item :label="$t('common.type')">
        <span class="limitLength" :title="$t('technology.serial.serialClass')">{{
          $t('technology.serial.serialClass')
        }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.name')">
        <span class="limitLength" :title="rule.ruleName">{{ rule.ruleName }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.modifyBy')">
        <span class="limitLength" :title="rule.modifyBy">{{ rule.modifyBy }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.modifyTime')">
        <span class="limitLength" :title="moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss')">
          {{ moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss') }}
        </span>
      </a-form-item>
    </a-form>
    <!--    序列号规则 -->
    <a-form
      v-if="rule.level === 2"
      class="no-bottom-form column-three-form"
      layout="inline"
      style="width: 100%;margin: 0 auto;"
    >
      <a-form-item :label="$t('common.type')">
        <span class="limitLength" :title="$t('technology.serial.serialRule')">{{
          $t('technology.serial.serialRule')
        }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.name')">
        <span class="limitLength" :title="rule.ruleName">{{ rule.ruleName }}</span>
      </a-form-item>
      <a-form-item :label="$t('technology.serial.code')">
        <span class="limitLength" :title="rule.ruleCode">{{ rule.ruleCode }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.modifyBy')">
        <span class="limitLength" :title="rule.modifyBy">{{ rule.modifyBy }}</span>
      </a-form-item>
      <a-form-item style="width: 55%" :label="$t('common.modifyTime')">
        <span class="limitLength" :title="moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss')">
          {{ moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss') }}
        </span>
      </a-form-item>
    </a-form>
    <!--    序列号实例-->
    <a-form
      v-if="rule.level === 3"
      class="no-bottom-form column-two-form"
      layout="inline"
      style="width: 100%;margin: 0 auto;"
    >
      <a-form-item :label="$t('common.type')">
        <span class="limitLength" :title="$t('technology.serial.serialInstance')">{{
          $t('technology.serial.serialInstance')
        }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.name')">
        <span class="limitLength" :title="rule.ruleName">{{ rule.ruleName }}</span>
      </a-form-item>
      <a-form-item :label="$t('technology.serial.code')">
        <span class="limitLength" :title="rule.ruleCode">{{ rule.ruleCode }}</span>
      </a-form-item>
      <a-form-item :label="$t('technology.serial.currentSerialNumber')">
        <span class="limitLength" :title="rule.currentSerialNum">{{ rule.currentSerialNum }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.modifyBy')">
        <span class="limitLength" :title="rule.modifyBy">{{ rule.modifyBy }}</span>
      </a-form-item>
      <a-form-item :label="$t('common.modifyTime')">
        <span class="limitLength" :title="moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss')">
          {{ moment(rule.modifyDate).format('YYYY-MM-DD HH:mm:ss') }}
        </span>
      </a-form-item>
    </a-form>
    <!--      序列号区段 start-->
    <a-spin :spinning="confirmLoading">
      <a-form-model
        v-if="rule.level === 2"
        ref="form"
        :model="form"
        style="width: 100%;margin: 0 auto;"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-model-item style="margin-bottom: 0px" :label="$t('technology.serial.lengthLimit')">
          <span>{{ allLength }}</span>
        </a-form-model-item>

        <a-form-model-item :label="$t('technology.serial.sectionDef')" required>
          <div>
            <a-button :disabled="!canEdit" type="primary" icon="plus" @click="handleAddSection">{{
              $t('technology.serial.addSection')
            }}</a-button>
            <a-row v-for="(r, index) in sectionList" :key="r.name">
              <a-button :disabled="!canEdit" @click="handleEditSection(r, index)" class="limitLength">{{
                r.name
              }}</a-button>
              <a-icon v-if="canEdit" type="delete" @click="handleDelSection(index)" style="margin-left:10px" />
              <a-icon
                type="arrow-up"
                v-if="index && canEdit"
                @click="handleUpSection(index)"
                style="margin-left:10px"
              />
              <a-icon
                type="arrow-down"
                v-if="index !== sectionList.length - 1 && canEdit"
                @click="handleDownSection(index)"
                style="margin-left:10px"
              />
            </a-row>
          </div>
        </a-form-model-item>
        <a-form-model-item :label="$t('common.description')" prop="description">
          <s-textarea :disabled="!canEdit" v-model.trim="form.description" :limit="255"></s-textarea>
        </a-form-model-item>
        <div style="text-align: center">
          <a-button v-action:add @click="handleOk" type="primary">{{ $t('common.save') }}</a-button>
          <a-button v-action:add style="margin-left: 8px" @click="handleReset">{{ $t('common.reset') }}</a-button>
          <a-button
            style="margin-left: 8px"
            :disabled="!initSectionList.length"
            type="primary"
            @click="handlePreview"
            >{{ $t('technology.serial.preview') }}</a-button
          >
        </div>
      </a-form-model>
    </a-spin>
    <!--      序列号区段 start-->
    <!--    序列号规则详情 End-->
    <section-modal ref="sectionModal" @ok="hanleSureSection"></section-modal>
    <rule-preview-modal ref="rulePreviewModal"></rule-preview-modal>
  </div>
</template>

<script>
import { STextarea } from '@/components';
import { updateSerialRule, updateSerialSection } from '@/api/technology/serial/serial';
import moment from 'moment';
import SectionModal from './SectionModal.vue';
import RulePreviewModal from './RulePreviewModal.vue';

export default {
  name: 'RuleConfigForm',
  components: {
    STextarea,
    SectionModal,
    RulePreviewModal
  },
  props: {
    rule: {
      type: Object,
      default: () => {}
    },
    sectionList: {
      type: Array,
      default: () => []
    },
    initSectionList: {
      type: Array,
      default: () => []
    }
  },
  filters: {
    attributeTypeFilter(value) {
      const map = {
        FIXED: 'Fixed',
        PARAM: 'Param',
        AUT0: 'Auto',
        DATETIME: 'DateTime'
      };
      return map[value] || '';
    }
  },
  watch: {
    sectionList: {
      handler() {
        if (this.sectionList && this.sectionList.length) {
          this.allLength = 0;
          this.sectionList.forEach(item => {
            if (item.sectionType === 'Param' || item.sectionType === 'Auto') {
              this.allLength += item.startLength;
            } else if (item.sectionType === 'Fixed') {
              this.allLength += item.parameter.length;
            } else if (item.sectionType === 'DateTime') {
              this.allLength += item.dateType.length;
            }
          });
        } else {
          this.allLength = '';
        }
      },
      deep: true
    },
    'rule.description': {
      handler(newValue) {
        this.$nextTick(() => {
          this.form.description = newValue;
        });
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.form.description = this.rule.description;
    });
  },
  data() {
    return {
      moment,
      allLength: '',
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 6
        },
        lg: {
          span: 4
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 18
        },
        lg: {
          span: 20
        }
      },
      confirmLoading: false,
      form: {
        description: ''
      },
      canEdit: this.$auth('add', this.$route.meta.permissionId)
    };
  },
  methods: {
    handleUpSection(index) {
      const beforeObj = this.sectionList[index - 1];
      this.$set(this.sectionList, index - 1, this.sectionList[index]);
      this.$set(this.sectionList, index, beforeObj);
    },
    handleDownSection(index) {
      const afterObj = this.sectionList[index + 1];
      this.$set(this.sectionList, index + 1, this.sectionList[index]);
      this.$set(this.sectionList, index, afterObj);
    },
    // 前端删除区段
    handleDelSection(index) {
      this.sectionList.splice(index, 1);
    },
    handleEditSection(section, index) {
      this.$refs.sectionModal.edit(section, index, this.sectionList, this.rule.startLength);
    },
    handleAddSection() {
      // 添加区段
      this.$refs.sectionModal.add(this.sectionList, this.rule.id, this.rule.startLength);
    },
    // sectionmodal 确定事件  更新区段
    hanleSureSection(callback) {
      // edit
      if (callback.index !== null) {
        this.$set(this.sectionList, callback.index, callback.section);
      } else {
        // add 新增
        this.sectionList.push(callback.section);
      }
    },
    // 保存规则 区段
    handleOk() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.sectionList.length <= 0) {
            this.$message.error('区段不能为空');
            return;
          }
          // 保存描述
          const req = {
            id: this.rule.id,
            ruleName: this.rule.ruleName,
            ruleCode: this.rule.ruleCode,
            description: this.form.description
          };
          this.confirmLoading = true;
          updateSerialRule(req)
            .then(() => {})
            .finally(() => {
              this.confirmLoading = false;
            });

          // 保存区段
          updateSerialSection({
            sectionList: this.sectionList
          })
            .then(res => {
              this.$message.success(this.$t(res.message));
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        }
      });
    },
    handleReset() {
      this.$emit('reset', this.rule.id);
      this.$nextTick(() => {
        this.form = {
          startLength: '',
          description: ''
        };
      });
    },
    // 预览
    handlePreview() {
      this.$refs.rulePreviewModal.open(this.rule, this.sectionList);
    },
    formatter(value) {
      return parseInt(value.toString().slice(0, 6)) || '';
    },
    selfValidator(rule, value, callback) {
      if (value.toString().length > 6) {
        callback('长度限制不能超过6位数');
      }
      callback();
    }
  }
};
</script>

<style></style>
<style scoped>
.limitLength {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.inlineForm .ant-form-item {
  width: 20%;
}
.oneLineForm .ant-form-item {
  width: 100%;
}
.no-bottom-form .ant-form-item {
  margin-bottom: 0px;
}
.column-two-form .ant-form-item {
  width: calc(50% - 16px);
  display: inline-block;
}
.column-three-form .ant-form-item {
  width: calc(33% - 16px);
  display: inline-block;
}
</style>
